﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Web;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel.Security;
using System.ServiceModel.Description;

namespace WFExtended.Framework.ServiceModel
{
    /// <summary>
    /// Wcf Proxy
    /// </summary>
    /// <typeparam name="T">Service Contract</typeparam>
    [DataContract]
    public class WcfProxy<T> : AWcfProxy
          where T : class
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="WcfProxy{T}"/> class.
        /// </summary>
        public WcfProxy() : this(0, TimeSpan.Zero)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="WcfProxy{T}"/> class.
        /// </summary>
        /// <param name="retryCount">The retry count.</param>
        /// <param name="retryDelay">The retry delay.</param>
        public WcfProxy(int retryCount, TimeSpan retryDelay)
        {
            _retryCount = retryCount;
            _retryDelay = retryDelay;
        }

        private int _retryCount;

        private TimeSpan _retryDelay;

        /// <summary>
        /// Gets or sets the type of the channel.
        /// </summary>
        /// <value>
        /// The type of the channel.
        /// </value>
        [DataMember]
        public ChannelType ChannelType { get; set; }


        /// <summary>
        /// Gets or sets the end point.
        /// </summary>
        /// <value>
        /// The end point.
        /// </value>
        public ServiceEndpoint EndPoint { get; set; }

        private ChannelFactory<T> _factory = null;

        private T _client = null;

        /// <summary>
        /// Gets the client.
        /// </summary>
        /// <value>
        /// The client.
        /// </value>
        /// <exception cref="System.NotSupportedException"></exception>
        public T Client
        {
            get
            {
                if(_client == null
                    || _factory == null
                    || (_factory.State != CommunicationState.Opened && _factory.State != CommunicationState.Opening))
                {
                    switch (ChannelType)
                    {
                        case ServiceModel.ChannelType.Standard:
                            if (this.EndPoint is ServiceEndpointConfiguration)
                            {
                                _factory = new ExtendedChannelFactory<T>(this.EndPoint.Name, _retryCount, _retryDelay);
                                foreach (var behavior in this.EndPoint.EndpointBehaviors)
                                    _factory.Endpoint.EndpointBehaviors.Add(behavior);
                            }
                            else
                                _factory = new ExtendedChannelFactory<T>(this.EndPoint, _retryCount, _retryDelay);
                            break;
                        case ServiceModel.ChannelType.Web:
                            if (this.EndPoint is ServiceEndpointConfiguration)
                            {
                                _factory = new ExtendedWebChannelFactory<T>(this.EndPoint.Name, _retryCount, _retryDelay);
                                foreach (var behavior in this.EndPoint.EndpointBehaviors)
                                    _factory.Endpoint.EndpointBehaviors.Add(behavior);
                            }
                            else
                                _factory = new ExtendedWebChannelFactory<T>(this.EndPoint, _retryCount, _retryDelay);
                            break;
                        default:
                            throw new NotSupportedException(
                                String.Format("Channel Type {0} Not Supported", ChannelType));
                    }
                    _factory.Open();
                    _client = _factory.CreateChannel();
                }

                return _client;
            }
        }

        /// <summary>
        /// Gets the type of the proxy.
        /// </summary>
        /// <value>
        /// The type of the proxy.
        /// </value>
        public override Type ProxyType
        {
            get { return typeof(T); }
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public override void Dispose()
        {
            try
            {
                if (_factory != null)
                    ((IExtendedChannel)_factory).Dispose();
            }
            catch { }

            _factory = null;
        }

    }
}
